package com.ruoyi.charge.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.solon.service.impl.ServiceImpl;
import com.ruoyi.charge.domain.Charger;
import com.ruoyi.charge.domain.ChargerGun;
import com.ruoyi.charge.mapper.ChargerMapper;
import com.ruoyi.charge.service.IChargerGunService;
import com.ruoyi.charge.service.IChargerService;
import com.ruoyi.common.web.exception.ServiceException;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
import org.noear.solon.data.annotation.Transaction;

/**
 * 充电桩 服务层实现
 *
 * @author laifeng
 */
@Component
public class ChargerServiceImpl extends ServiceImpl<ChargerMapper, Charger> implements IChargerService {

    @Inject
    ChargerMapper chargerMapper;
    @Inject
    IChargerGunService chargerGunService;

    @Override
    @Transaction
    public boolean saveCharger(Charger charger) {
        // 判断是否存在
        String sn = StrUtil.padPre(charger.getSn(), 14, "0");
        charger.setSn(sn);
        boolean exists = this.exists(QueryWrapper.create().eq(Charger::getSn, charger.getSn()));
        if (exists) {
            throw new ServiceException("设备编号已存在");
        }

        boolean result = this.save(charger);
        if (result) {
            // 保存充电枪
            for (int i = 1; i <= charger.getGunNum(); i++) {
                ChargerGun chargerGun = new ChargerGun();
                chargerGun.setChargerId(charger.getId());
                chargerGun.setNumber(Convert.toStr(i + 1));
                chargerGun.setChargerSn(charger.getSn());
                chargerGunService.save(chargerGun);
            }
        }
        return result;
    }

    @Override
    @Transaction
    public boolean updateCharger(Charger charger) {
        String sn = StrUtil.padPre(charger.getSn(), 14, "0");
        charger.setSn(sn);
        boolean exists = this.exists(QueryWrapper.create().eq(Charger::getSn, charger.getSn()).ne(Charger::getId, charger.getId()));
        if (exists) {
            throw new ServiceException("设备编号已存在");
        }
        return this.updateById(charger);
    }
}
